package com.easydisk.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easydisk.constant.CommonConstant;
import com.easydisk.response.R;
import com.easydisk.user.config.RedisServer;
import com.easydisk.user.dao.RoleMapper;
import com.easydisk.user.dao.UserAndRoleMapper;
import com.easydisk.user.dao.UserMapper;
import com.easydisk.user.model.entity.User;
import com.easydisk.user.pojo.LoginUser;
import com.easydisk.user.service.LoginService;
import com.easydisk.common.util.JwtUtil;
import com.easydisk.common.util.UserIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserAndRoleMapper userAndRoleMapper;

    @Autowired
    private RedisServer redisServer;

    @Resource
    private PasswordEncoder encoder;


    /**
     * 账号密码登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public R login(String username,String password) throws Exception {
        //生成对象令牌
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(username,password);
        //进行用户验证
        Authentication authentication=authenticationManager.authenticate(authenticationToken);
        //验证失败
        if(Objects.isNull(authentication)){
            //验证失败,跳转到失败页面
           throw new RuntimeException("验证失败");
        }
        //验证通过，获取用户
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //生成token
        String token= JwtUtil.generateToken(loginUser.getUsername(), CommonConstant.LOGIN_USER_ID,
                loginUser.getUser().getId(),CommonConstant.ONE_DAY_LONG);

        return  R.data(token);
    }


    /**
     * 验证码登录（如何复用接口）
     * @param username      haixing
     * @param code
     * @return
     */
    @Override
    public R loginByCode(String username, String code) {
        //通过数据库查找是否存在这个用户
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user=userMapper.selectOne(queryWrapper);
        //对比验证码是否正确
        if(!code.equals("888888"))
            return R.fail("验证码错误");
        //生成token

        //参数列表JwtUtil.generateToken(rPanUser.getUsername(),
        //                CommonConstant.LOGIN_USER_ID, rPanUser.getUserId(), CommonConstant.ONE_DAY_LONG);
        String token= JwtUtil.generateToken(user.getUsername(), CommonConstant.LOGIN_USER_ID,
                user.getId(),CommonConstant.ONE_DAY_LONG);
        return R.data(token);
    }

    /**
     * 找回密码
     * @param newPassword
     * @param username
     * @return
     */
    @Override
    public R findPassword(String newPassword, String username,String code) {
        //比对输入code是否为预期的code

        //修改数据库中的username用户的password
        return R.success();
    }

    /**
     * 用户修改密码
     * @param newPassword
     * @param password
     * @return
     */
    @Override
    public R changePassword(String newPassword, String password) {
        Long userID= UserIdUtil.get();
        //判断密码是否和数据库里面的相同
        User user = userMapper.selectById(userID);
        //相同则更新，不同则返回密码错误
        if(!encoder.matches(password,user.getPassword())) {
            return R.fail("原密码输入错误");
        }
        user.setPassword(encoder.encode(newPassword));
        userMapper.updateById(user);
        return R.success("修改成功");
    }


    /**
     * 退出登录
     * @return
     */
    @Override
    public R loginout() {
        //获取userID
        Long userid = UserIdUtil.get();
        //删除redis中存放的token信息
        return R.success();
    }
}
